<template>
    <div class="cart-container wrapper">
        <div class="cart-wrap">
            <!-- 标题区域开始 -->
            <div class="title-wrap">
                <span class="checked-all">
                    <TridentCheckbox style="color:#f3514f;" @change="checkAll" :modelValue="cartStore.isCheckAll" v-if="cartStore.validList.length > 0">全选</TridentCheckbox>
                </span>
                <span class="goods-wrap">商品信息</span>
                <span class="price-wrap">单价</span>
                <span>数量</span>
                <span>小计</span>
                <span>操作</span>
            </div>
            <!-- 标题区域结束 -->

            <!-- 内容区域开始 -->
            <div class="content-wrap">
                <!-- 有效商品区域开始 -->
                <template v-if="cartStore.validList.length > 0">
                    <div class="item-wrap" v-for="(item, index) in cartStore.validList" :key="index">
                        <div class="checked-all">
                            <TridentCheckbox style="color:#f3514f;" @change="$event=>checkOne(item.id,$event)" :modelValue="item.is_checked == 1"/>
                        </div>

                        <!-- 商品信息 -->
                        <div class="goods-wrap">
                            <div class="cover-wrap" @click="$router.push({path: '/goods-detail', query:{id: item.goods_id}})">
                                <img :src="global.FILE_DOMAIN+item.goods.cover_url" alt="">
                            </div>

                            <div class="info-wrap">
                                <span class="goods-name ellipsis-2">{{ item.goods.name }}</span>

                                <!-- 选择规格组件 -->
                                <CartSku @change="$event=>updateCartSku(item,$event)" :goods_sepc_option_text="item.goods_sepc_option_text" :goods_id="item.goods_id" :skuId="item.goods_sku_id" :goodsSkuImg="item.goods.cover_url"/>
                            </div>
                        </div>

                        <!-- 价格 -->
                        <div>
                            <p>￥{{ (item.new_price/100).toFixed(2) }}</p>
                            <p class="mark-down" v-if="item.goods.price > item.new_price">
                                <span>比加入时降价</span>
                                <span>￥{{ ((item.goods.price - item.new_price)/100).toFixed(2) }}</span>
                            </p>
                        </div>

                        <!-- 数量 -->
                        <div class="number-box">
                            <Numbox @change="$event=>changeNum(item,$event)" :modelValue="item.num" :max="item.inventory_num"/>
                        </div>

                        <!-- 小计 -->
                        <div class="subtotal">￥{{ (item.num * item.new_price/100).toFixed(2) }}</div>
                        
                        <!-- 操作 -->
                        <div class="action-wrap">
                            <p><a class="green" @click="handleDeleteCart(item)" href="javascript:;">删除</a></p>
                        </div>
                    </div>
                </template>
                <Empty v-else/>
                <!-- 有效商品区域结束 -->

                <template v-if="cartStore.invalidList.length > 0">
                    <div class="failure-title-wrap">失效商品</div>

                    <!-- 失效商品区域开始 -->
                    <div class="item-wrap" v-for="(item, index) in cartStore.invalidList" :key="index">
                        <div class="checked-all">
                        </div>

                        <!-- 商品信息 -->
                        <div class="goods-wrap">
                            <div class="cover-wrap" @click="$router.push({path: '/goods-detail', query:{id: item.goods_id}})">
                                <img :src="global.FILE_DOMAIN+item.goods.cover_url" alt="">
                            </div>

                            <div class="info-wrap">
                                <span class="goods-name ellipsis-2">{{ item.goods.name }}</span>
                                <span class="goods-sku-txt ellipsis-1">{{ item.goods_sepc_option_text }}</span>
                            </div>
                        </div>

                        <!-- 价格 -->
                        <div>
                            <p>￥{{ (item.new_price/100).toFixed(2) }}</p>
                            <p class="mark-down" v-if="item.goods.price > item.new_price">
                                <span>比加入时降价</span>
                                <span>￥{{ ((item.goods.price - item.new_price)/100).toFixed(2) }}</span>
                            </p>
                        </div>

                        <!-- 数量 -->
                        <div class="number-box">
                            <Numbox @change="$event=>changeNum(item,$event)" :modelValue="item.num" :max="item.inventory_num"/>
                        </div>

                        <!-- 小计 -->
                        <div class="subtotal">￥{{ (item.num * item.new_price/100).toFixed(2) }}</div>
                    
                        <!-- 操作 -->
                        <div class="action-wrap">
                            <p><a class="green" @click="handleDeleteCart(item)" href="javascript:;">删除</a></p>
                        </div>
                    </div>
                    <!-- 失效商品区域结束 -->
                </template>
            </div>
            <!-- 内容区域结束 -->

            <!-- 底部操作区域开始 -->
            <div class="total-wrap">
                <div class="batch">
                    <template v-if="cartStore.validList.length > 0">
                        <TridentCheckbox style="color:#f3514f;" @change="checkAll" :modelValue="cartStore.isCheckAll">全选</TridentCheckbox>
                        <a @click="handleBatchDeleteCart" href="javascript:;">删除商品</a>
                    </template>
                    <a style="color: #27BA9B;" @click="handleClearInvalidCart" href="javascript:;" v-if="cartStore.invalidList.length > 0">清空失效商品</a>
                </div>

                <div class="total" v-if="cartStore.validList.length > 0">
                    <span>
                        共 {{ cartStore.validTotal }} 件商品，已选择 {{ cartStore.checkedTotal }} 件，
                    </span>
                    <span class="summation">商品合计：</span>
                    <span class="amount"><i class="symbol">¥</i> {{ (cartStore.checkedAmount/100).toFixed(2) }}</span>
                    <span @click="$router.push({path: '/confirm-order', query: {mode: 2}})" class="create-order-btn">下单结算</span>
                </div>
            </div>
        </div>

        <!-- 猜你喜欢区域开始 -->
        <GuessLike :cid="1301"/>
        <!-- 猜你喜欢区域结束 -->

        <!-- 返回顶部组件 -->
        <BackTop @backTop="backTop" :isShowBackTop="isShowBackTop"></BackTop>
    </div>
</template>

<script setup>
import { inject, onMounted, ref, watch } from "vue"
import { ElNotification, ElMessageBox } from 'element-plus';

import {useCartStore} from "@/stores/modules/cart"
import CartSku from './components/CartSku.vue'

import useScroll from '@/utils/useScroll'


// ---------------- 返回顶部功能开始 ----------------
const isShowBackTop = ref(false)
const {scrollTop, scrollToTop} = useScroll()
watch(scrollTop, (oldValue, newValue) => {
    isShowBackTop.value = oldValue > 800 ? true : false
})

// 返回顶部
const backTop = () => {
    scrollToTop()
}
// ---------------- 返回顶部功能结束 ----------------


// ---------------- 定义全局变量开始 ----------------
// 定义购物车存储
const cartStore = useCartStore()

// 全局属性
const global = inject('global')

// ---------------- 定义全局变量结束 ----------------



// ---------------- 挂载页面功能开始 ----------------
onMounted(async () => {
  await cartStore.getCartList()
})
// ---------------- 挂载页面功能结束 ----------------



// ---------------- 全选商品功能结束 ----------------
const checkAll = async () => {
  if (cartStore.validList.length == 0) {
    return false
  }
  
	await cartStore.checkAllCart(!cartStore.isCheckAll)
}
// ---------------- 全选商品功能结束 ----------------



// ---------------- 勾选商品功能开始 ----------------
// 延时器
const timer = ref(null)

// 单选商品
const checkOne =  (id, checked) => {
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout( async () => {
		await cartStore.editCart({ids: id + '', is_checked: checked ? 1 : 0})
        ElNotification({
            type: 'success',
            message: '编辑成功'
        })
	}, 500)
}
// ---------------- 勾选商品功能结束 ----------------



// ---------------- 修改数量功能开始 ----------------
const changeNum = async (item, num) => {
    // 判断库存
    if (num > item.inventory_num) {
        ElNotification({type: 'error', message: '库存不足'})
        return
    }

    // ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)

    // 重新启动延时器
	timer.value = setTimeout( async () => {
		await cartStore.editCart({ids: item.id + '', num})
        ElNotification({type: 'success', message: '修改成功'})
	}, 500)
  
}
// ---------------- 修改数量功能结束 ----------------



// ---------------- 修改规格功能开始 ----------------
const updateCartSku = async (item, newSku) => {
    // sku选项变化了，则需要更新操作
    if (item.goods_sku_id != newSku.skuId) {
        await cartStore.editCartSku({
            id: item.id,
            num: item.num,
            goods_cover_url: newSku.cover_url,
            goods_name: item.goods.name,
            newSku: {
                skuId: newSku.skuId,
                price: newSku.price,
                goods_cover_url: newSku.cover_url,
                inventory_num: newSku.inventory_num,
                specsText: newSku.specsText,
            }
        })

        ElNotification({type: 'success', message: '选择SKU完成'})
    }
}
// ---------------- 修改规格功能结束 ----------------



// ---------------- 单项删除功能开始 ----------------
const handleDeleteCart = (item) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
        await cartStore.deleteCart(item.id)
        ElNotification({type: 'success', message: '删除成功'});
    }).catch(() => {
    })
}
// ---------------- 单项删除功能结束 ----------------



// ---------------- 批量删除功能开始 ----------------
const handleBatchDeleteCart = () => {
    if (cartStore.checkedTotal == 0) {
        ElNotification({type: 'error', message: '请选择要删除的商品'})
        return
    }

    ElMessageBox.confirm('确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
    }).catch(() => {
    })
}
// ---------------- 批量删除功能结束 ----------------



// ---------------- 清空无效商品开始 ----------------
const handleClearInvalidCart = () => {
    if (cartStore.invalidList.length <= 0) {
        ElNotification({type: 'error', message: '没有失效商品'})
        return false
    }

    ElMessageBox.confirm('确定要清除失效商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        await cartStore.clearInvalidCart()
        ElNotification({type: 'success', message: '清空失效商品成功'});
    }).catch(() => {
    })
}
// ---------------- 清空无效商品结束 ----------------
</script>

<style scoped lang="scss">
.cart-container {
    margin-bottom: 20px;
    padding-top: 200px;
    .cart-wrap {
        background-color: #fff;
        color: #666;
        // 标题区域
        .title-wrap {
            display: flex;
            justify-content: space-evenly;
            align-items: center;
            height: 50px;
            span {
                width: 18%;
                text-align: center;
                font-size: 18px;
            }
            .checked-all {
                width: 10%;
            }
            .goods-wrap {
                width: 35%;
            }
        }

        // 内容区域
        .content-wrap {
            .item-wrap {
                display: flex;
                justify-content: space-evenly;
                align-items: center;
                padding: 20px 0;
                border-top: 1px solid #F5F5F5;
                > div {
                    width: 18%;
                    text-align: center;
                    .mark-down {
                        color: #CF4444;
                        padding-top: 10px;
                    }
                }

                // 商品信息
                .goods-wrap {
                    display: flex;
                    align-items: center;
                    width: 35%;
                    text-align: left;
                    .cover-wrap {
                        width: 100px;
                        height: 100px;
                        border: 1px solid #ccc;
                        cursor: pointer;
                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }

                    .info-wrap {
                        flex: 1;
                        padding-left: 10px;
                        .goods-name {
                            line-height: 20px;
                        }
                        .goods-sku-txt {
                            margin-top: 10px;
                            background-color: #F5F5F5;
                            height: 20px;
                            line-height: 20px;
                            font-size: 14px;
                            padding: 0 6px;
                        }
                    }
                }

                .checked-all {
                    width: 10%;
                }

                // 数量
                .number-box {
                    display: flex;
                    justify-content: center;
                }

                // 小计
                .subtotal {
                    color: #CF4444;
                }

                // 操作
                .action-wrap {
                    p {
                        a {
                            color: #CF4444;
                        }
                    }
                }
            }

            .failure-title-wrap {
                font-size: 18px;
                font-weight: bold;
                padding: 20px 10px;
                color: #ccc;
                border-top: 1px dashed #ccc;
                border-bottom: 1px dashed #ccc;
            }
        }

        .total-wrap {
            padding: 0 48px;
            height: 80px;
            border-top: 1px solid $main-color;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .batch {
                a {
                    margin-left: 20px;
                }
            }
            .total {
                .amount {
                    color: $price-color;
                    font-size: 20px;
                    .symbol {
                        font-size: 16px;
                    }
                }
                .summation {
                    font-weight: bold;
                }

                .create-order-btn {
                    padding: 15px 30px;
                    background-color: $main-color;
                    color: #fff;
                    margin-left: 30px;
                    border-radius: 2px;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>